﻿using System.Linq;

namespace ForceSystem.Untangler
{
    public class UntangledContext
    {
        public UntangledNamespaceCollection Namespaces { get { return _namespaces; } }
        public UntangledAssemblyCollection  Assemblies { get { return _assemblies; } }
        public UntangledTypeCollection      Types { get { return _types; } }

        public void AddAssembly(string filename)
        {
            var assembly = new UntangledAssembly(this, filename);
            _assemblies.Add(assembly);

            foreach (var uns in assembly.Namespaces)
            {
                var ns = FindNamespace(uns);
                foreach (var type in uns.Types.Where(type => !ns.Types.Contains(type)))
                {
                    ns.Types.Add(type);
                }

                // Sort type by name.
                ns.Types = UntangledTypeCollection.FromEnumeable(ns.Types.OrderBy(t => t.Name));
            }

            foreach (var type in assembly.Types.Where(type => !_types.Contains(type)))
            {
                _types.Add(type);
            }

            // Sort type by name.
            _types = UntangledTypeCollection.FromEnumeable(_types.OrderBy(t => t.Name));
        }

        UntangledNamespace FindNamespace(UntangledNamespace uns)
        {
            foreach (var namesapce in _namespaces.Where(namesapce => string.CompareOrdinal(namesapce.Name, uns.Name) == 0))
            {
                return namesapce;
            }

            var newNs = new UntangledNamespace(uns.Name);
            _namespaces.Add(newNs);

            return newNs;
        }

        readonly UntangledAssemblyCollection _assemblies = new UntangledAssemblyCollection();
        readonly UntangledNamespaceCollection _namespaces = new UntangledNamespaceCollection();
        UntangledTypeCollection _types = new UntangledTypeCollection();
    }
}
